<template>
  <div>
    <upload-excel :on-success="handleSuccess" />
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    // 导入后的文件需要做处理
    transExcel(results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(item => {
        const obj = {}

        const zhKeys = Object.keys(item)
        zhKeys.forEach(zhKey => {
          const enKey = userRelations[zhKey]
          if (enKey === 'correctionTime' || enKey === 'timeOfEntry') {
            obj[enKey] = new Date(formatExcelDate(item[zhKey]))
          } else {
            obj[enKey] = item[zhKey]
          }
        })
        return obj
      })
    },
    async handleSuccess({ header, results }) {
      try {
        const arr = this.transExcel(results)
        console.log('转换之后的格式', arr)
        // 调用上传的接口
        const res = await importEmployee(arr)
        console.log('调用上传的接口', res)
        // 成功后，返回刚才的页面
        this.$router.back()
        this.$message.success('操作成功')
      } catch (err) {
        // console.log(err)
        this.$message.error(err.message)
      }
    }
  }
}
</script>
